﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DesignLife.Admin.Business;

namespace DesignLife.Admin
{
    public partial class NewsManager : System.Web.UI.Page
    {
        BusinessNews_Category bsNewsCategory = new BusinessNews_Category();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["AddNews"] = true;
                Session["AddCate"] = true;
                if (Session["Username"] != null)
                {
                    bindDataNews();
                    bindDataCate();
                    bindDataParrent();
                }
                else
                {
                    Response.Redirect("AdminLogin.aspx");
                }
                if (Session["Role"] == "1")
                {
                    ckbStatus.Enabled = false;
                }
                else
                {
                    ckbStatus.Enabled = true;
                }
            }
        }

        private void bindDataParrent()
        {
            DropDownList1.Items.Clear();
            DropDownList1.Items.Add(new ListItem("Service", "service"));
            DropDownList1.Items.Add(new ListItem("Introdution", "introdution"));
            DropDownList1.DataBind();
        }

        private void bindDataCate()
        {
            DataTable dataList;
            DataTable data;
            dataList = bsNewsCategory.getCate();
            gvCate.DataSource = dataList;
            gvCate.DataBind();
            data = bsNewsCategory.getListCate();
            ddlCategory.DataSource = data;
            ddlCategory.DataTextField = "CategoryName";
            ddlCategory.DataValueField = "CategoryID";
            ddlCategory.DataBind();
        }

        private void bindDataNews()
        {
            DataTable data;
            data = bsNewsCategory.getNews();
            gvNews.DataSource = data;
            gvNews.DataBind();
        }

        protected void gvNews_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["AddNews"] = false;
            GridViewRow row = gvNews.SelectedRow;
            int id = int.Parse(row.Cells[0].Text);
            ViewState["IDNews"] = id;
            txtTitle.Text = row.Cells[1].Text;
            Image1.ImageUrl = "~/UploadFiles/Images/" + row.Cells[2].Text;
            ViewState["Image"] = row.Cells[2].Text;
            txtContent.Text = row.Cells[3].Text;
            bindDataCate();
            ddlCategory.Items.FindByText(row.Cells[5].Text).Selected = true;
            ckbStatus.Enabled = true;
            ckbStatus.Checked = Convert.ToBoolean(row.Cells[6].Text);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string title = txtTitle.Text;
            string content = txtContent.Text;
            string link = FileUpload1.FileName;
            DateTime date = DateTime.Now;
            bool check = ckbStatus.Checked;
            int idCate = Convert.ToInt32(ddlCategory.SelectedItem.Value);
            
            if (Session["AddNews"].Equals(true))
            {
                if (FileUpload1.HasFile)
                {
                    link = SaveImage(link);
                }
                bsNewsCategory.addNews(title, link, content, date, idCate);
                Response.Redirect("NewsManager.aspx");
            }
            else
            {
                int id = (int)ViewState["IDNews"];
                if(FileUpload1.HasFile)
                {
                    link = SaveImage(link);
                }
                else
                {
                    link = (string) ViewState["Image"];
                }
                bsNewsCategory.updateNew(title, link,content,date,idCate,check, id);
                Response.Redirect("NewsManager.aspx");
            }
        }

        private string SaveImage(string link)
        {
            if (IsImage(link))
            {
                if (!Directory.Exists(Server.MapPath("/") + "UploadFiles/Images/"))
                {
                    Directory.CreateDirectory(Server.MapPath("/") + "UploadFiles/Images/");
                }
                link = DateTime.Now.ToString("dd.MM.yyyy") + "_" + Guid.NewGuid().ToString() + link;
                FileUpload1.SaveAs(Server.MapPath("/") + "UploadFiles/Images/" + link);
            }
            else
            {
                throw new Exception("Not support File type: " + FileUpload1.PostedFile.ContentType);
            }
            return link;
        }

        public static bool IsImage(string filename)
        {
            if (String.IsNullOrEmpty(filename)) return false;
            var reg = new Regex(".[jpg|png|gif]$");
            return reg.IsMatch(filename.ToLower());
        }

        protected void gvNews_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvNews.PageIndex = e.NewPageIndex;
            DataTable data;
            data = bsNewsCategory.getNews();
            gvNews.DataSource = data;
            gvNews.DataBind();
        }

        protected void btnSubmitCate_Click(object sender, EventArgs e)
        {
            
            string ctName = txtCTName.Text;
            string link = txtLink.Text;
            string parrent = DropDownList1.SelectedItem.Value;
            string summary = txtSummary.Text;
            bool sttCT = ckbStatusCate.Checked;
            if(Session["AddCate"].Equals(true))
            {
                bsNewsCategory.addCate(ctName,link,parrent,summary);

            }
            else
            {
                int id = (int)ViewState["IDCate"];
                bsNewsCategory.updateCate(ctName,link,parrent,summary,sttCT,id);
            }
            bindDataCate();
            Response.Redirect("NewsManager.aspx");
        }

        protected void gvCate_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["AddCate"] = false;
            GridViewRow row = gvCate.SelectedRow;
            int id = int.Parse(row.Cells[0].Text);
            ViewState["IDCate"] = id;
            txtCTName.Text = row.Cells[1].Text;
            txtLink.Text = row.Cells[2].Text;
            bindDataParrent();
            string text = row.Cells[3].Text;
            bindDataParrent();
            DropDownList1.Items.FindByValue(text).Selected = true;
            txtSummary.Text = row.Cells[4].Text;
            ckbStatusCate.Enabled = true;
            ckbStatusCate.Checked = Convert.ToBoolean(row.Cells[5].Text);
        }

        

    }
}